import { Modal } from 'antd'
import { QRCode } from 'react-qrcode-logo'
import { MAX_CHECK_COUNT, TRADE_STATE } from './constants'
import api from './api'
function scanQRCodePay({ orderNo, code_url, callback }) {
  let interval
  const modal = Modal.info({
    title: '请支付',
    content: <QRCode value={code_url} />,
    width: 280,
    okText: '取消',
    onOk: () => {
      closeModal()
    }
  })
  const closeModal = () => {
    interval && clearInterval(interval)
    interval = null
    modal.destroy()
    callback?.()
  }
  let checkCount = 0
  interval = setInterval(() => {
    // 如果检查次数已经大于最大检查次数，直接关闭跳回订单页
    if (++checkCount > MAX_CHECK_COUNT) {
      return closeModal()
    }
    api.get(`/api/payment/order/${orderNo}`).then(response => {
      const { trade_state } = response.data
      console.log('response.data::::', response.data);
      if (trade_state !== TRADE_STATE.NOTPAY) {
        return closeModal()
      }
    }, error => {
      console.error('查询订单支付状态失败', error)
      closeModal()
    })
  }, 1000)
}

export {
  scanQRCodePay
}